package com.wwl.cms.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.DateUtils;
import com.wwl.cms.basic.PagedOutput;
import com.wwl.cms.basic.utils.R;
import com.wwl.cms.basic.utils.SnowFlakeUtils;
import com.wwl.cms.dto.UserDto;
import com.wwl.cms.entity.UserBean;
import com.wwl.cms.repository.UserInfoRepository;
import com.wwl.cms.service.ShiroService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.Authorization;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wwl
 * @version 1.0
 * @date 2021/2/9 18:46
 * @description:https://www.jianshu.com/p/99a5ec5c3bd5
 */
@Api(value = "/user", description = "用户管理", tags = {"user"})
@RestController
@RequestMapping(value = "/user", produces = {"application/json"})
public class UserController {
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private ShiroService shiroService;


    @ApiOperation("用户列表动态查询")
    @RequestMapping(value = "/findPage", method = RequestMethod.POST)
    public Object list(@RequestBody UserDto userDto) {

        //创建匹配器，需要查询条件请修改此处代码
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())//全部模糊
                .withMatcher("age", m -> m.exact())//精确匹配
                .withIgnoreNullValues()//忽略null值
                .withIgnorePaths("id");//忽略id

        UserBean userBean = new UserBean();
        BeanUtils.copyProperties(userDto, userBean);
        //创建实例
        Example<UserBean> example = Example.of(userBean, matcher);
        //分页构造
        Pageable pageable = PageRequest.of(userDto.getPageNum() - 1, userDto.getPageSize());
        Page page = userInfoRepository.findAll(example, pageable);
        return new PagedOutput(userDto.getPageSize(), userDto.getPageNum(), page.getTotalElements(), page.getContent());
        //https://blog.csdn.net/weixin_44216706/article/details/106496298 参考网址
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    @ApiOperation(value = "用户详情", authorizations = {@Authorization(value = "token")})
    public UserBean detail(@ApiParam(value = "id") @RequestParam(value = "id", required = false) Long id) {
        UserBean userBean = userInfoRepository.findFirstById(id);
        return userBean;

    }

    @ApiOperation("添加用户数据")
    @RequestMapping(value = "/saveUserInfo", method = RequestMethod.POST)
    public R saveUserInfo(@RequestBody UserBean user) {
        if (user==null || !StringUtils.hasText(user.getName())){
            return  R.error("参数有误!!!");
        }
        UserBean userBean = new UserBean();
        BeanUtils.copyProperties(user,userBean);
        if (userBean.getId()==null){
            userBean.setId((Long) SnowFlakeUtils.getId(0L));
        }
       return new R(userInfoRepository.saveAndFlush(user)) ;


    }

    @ApiOperation("登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public R login(@ApiParam(value = "name") @RequestParam(value = "name", required = false) String name,
                   @ApiParam(value = "pwd") @RequestParam(value = "pwd", required = false) String pwd) {
        UserBean userBean = userInfoRepository.findByNameAndPwd(name, pwd);
        R token = null;
        if (null == userBean) {
            return R.error("未查询到用户信息！！！");
        } else {
            //生成token，并保存到数据库
            token = shiroService.createToken(userBean.getId());
        }

        return token;
    }

    @ApiOperation("阿里巴巴easyExcel数据导出")
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void exportExcel(@ApiParam(value = "size") @RequestParam(value = "size") Integer size, HttpServletResponse response) {
        try {
            //获取数据
            System.out.println("开始查询导出：" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            String name = "";
            List<String> list = new ArrayList<>();
            list.add("id");
            Pageable pageable = PageRequest.of(0, size, Sort.by(Sort.Direction.ASC, "id"));
            Page<UserBean> page = userInfoRepository.findAll(pageable);
            List<UserDto> data = page.getContent().stream().map(it -> {
                UserDto userDto = new UserDto();
                BeanUtils.copyProperties(it, userDto);
                return userDto;
            }).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(data)) {
                data.add(new UserDto());
            }
            System.out.println("开始导出：" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            //attachment指定独立文件下载  不指定则回浏览器中直接打开
            String fileName = "业务订单导出_" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            //导出excel
            EasyExcel.write(response.getOutputStream(), UserDto.class).sheet("合伙人业务订单").doWrite(data);
            System.out.println("导出结束：" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            /*  log.error("业务订单导出异常打印:", e);*/
        } finally {
            try {
                response.flushBuffer();
            } catch (IOException e) {
                /* log.error("业务订单导出输出流关闭失败: {}", e);*/
            }
        }
    }


}
